package com.hycat.mail.product.service.impl;

import com.hycat.mail.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hycat.mail.common.utils.PageUtil;
import com.hycat.mail.common.utils.Query;

import com.hycat.mail.product.dao.AttrGroupDao;
import com.hycat.mail.product.entity.AttrGroupEntity;
import com.hycat.mail.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
@Slf4j
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public PageUtil queryPage(Map<String, Object> params, Long catelogId) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                catelogId == 0 ? new QueryWrapper<AttrGroupEntity>() : getWrapper(params, catelogId));

        PageUtil pageUtils = new PageUtil(page);
        List<AttrGroupEntity> list = (List<AttrGroupEntity>) pageUtils.getList();
        List<AttrGroupEntity> collect = list.stream().map((attrgroup) -> {
            List<Long> longs = categoryService.categoryPath(attrgroup.getAttrGroupId());
            attrgroup.setCategoryPath(longs);
            return attrgroup;
        }).collect(Collectors.toList());

        pageUtils.setList(collect);

        return pageUtils;
    }

    public QueryWrapper<AttrGroupEntity> getWrapper(Map<String, Object> params, Long catelogId){
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId);
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.like("attr_group_id", key).or().like("attr_group_name", key);
            });
        }
        return wrapper;
    }

}